var userStore;
var user
var grid;
var userLevelCombo;

var usersSupportObj = {
	cancelUser : function() {
		var panel = $F('activePanel');
		$('activePanel').value = '';
		$('formType').value = '';
		
		// Display add form
		new Effect.SlideUp('formNewUser', {direction: 'top', duration: .2});
		
		/*
		 * Clear form divs
		 */
		$('userForm0').innerHTML = '';
		$('userForm1').innerHTML = '';
		
		// Turn on add button
		$('buttonNew'+panel).style.display = 'block';	
		
		/*
		 * Turn all form elements back on
		 */
		$('ptiContainer').style.display = '';
		$('userLevelContainer').style.display = '';
	},
	openNewUserForm : function(panel) {
		// Turn off add button
		$('buttonNew'+panel).style.display = 'none';
		
		// Set hidden field defaults
		$('formAction').value = 'add';
		$('uID').value = '0';
		$('activePanel').value = panel;
		
		/*
		 * Clear form
		 */
		this.clearUserForm();	
		
		/*
		 * Drop form into correct div
		 */
		$('userForm'+panel).innerHTML = $('formDiv').innerHTML;
		
		/*
		 * Toggle form specific elements		 
		 */
		if (panel == 0) {
			$('formType').value = 'userStaff';
			$('ptiContainer').style.display = 'none';
		} else if (panel == 1) {
			$('formType').value = 'userSharedResource';
			$('userLevelContainer').style.display = 'none';
			
			/*
			 * Get random password for this form
			 */
			var randomPassword = randomString(5);
			$('uPassword').value = randomPassword;
			$('uPasswordConfirm').value = randomPassword;
		}
		
		// Display add form
		new Effect.SlideDown('formNewUser', {direction: 'top', duration: .3});
	},
	clearUserForm : function() {
		// Clear all form elements
		$('uNameFirst').value   = '';
		$('uNameLast').value    = '';
		$('uEmail').value           = '';
		$('uUserName').value     = '';
		$('uPassword').value        = '';
		$('uPasswordConfirm').value = '';
		$('uPTI').value = '';
	},
	renderUsersGrid : function(whatUsers) {
		/*
		 * Destroy grid first if it exists
		 */
		if (!userLevelCombo) {
			userLevelCombo = new Ext.form.ComboBox({
	               triggerAction: 'all',
	               transform:'uUserLevelForGrid',
	               lazyRender:true
			});       
		}
		
		if (whatUsers == 'staff') {
			var renderDiv = 'userGrid';
		} else if (whatUsers == 'resource') {
			var renderDiv = 'resourceShareUserGrid';
		}
		
		// shorthand alias
	    var fm = Ext.form;
		var Ed = Ext.grid.EditorGridPanel;
	
		// Create the data source
		userStore = new Ext.data.Store({
		    proxy: new Ext.data.HttpProxy({
				url: 'ajaxDirector.php?handler=getUsers&whatUsers='+whatUsers
		    }),			
		    reader: new Ext.data.JsonReader({
		        root: 'Users',
		        id: 'StaffID'
		    }, [
		    {name: 'StaffID', mapping: 'StaffID'},
			{name: 'Delete', mapping: 'Delete'},
		    {name: 'StaffFName', mapping: 'NameFirst'},
			{name: 'StaffLName', mapping: 'NameLast'},
			{name: 'StaffEmail', mapping: 'Email'},
			{name: 'StaffPhone', mapping: 'Phone'},
			{name: 'UserName', mapping: 'Userid'},
			{name: 'Password', mapping: 'Password'},
			{name: 'LevelSecurity', mapping: 'LevelSecurity'},
			{name: 'PTIAffiliation', mapping: 'PTIAffiliation'}
		    ])		
		});
		
		// Define the column model
		var colModel = new Ext.grid.ColumnModel([
			 {dataIndex: 'StaffID', hidden: 'true'}
			,{dataIndex: 'Delete', align: 'center', width: 40, header: "", sortable: false}
			,{
			 	header:    "First Name", 
				width:     90, 
				dataIndex: 'StaffFName',
				editor: new fm.TextField({
	            	allowBlank: true
	           	})
			}
			,{
			 	header:    "Last Name", 
				width:     100, 
				dataIndex: 'StaffLName',
				editor: new fm.TextField({
	            	allowBlank: true
	           	})
			}
			,{
				header: "Email Address", 
				align: 'left', 
				width: 180, 
				dataIndex: 'StaffEmail',
				editor: new fm.TextField({
	            	allowBlank: true
	           	})
			}
			,{
				header: "Phone", 
				align: 'left', 
				width: 100, 
				dataIndex: 'StaffPhone',
				editor: new fm.TextField({
	            	allowBlank: true
	           	})
			}
			,{
				header: "PTI Affiliation", 
				align: 'left', 
				width: 145, 
				dataIndex: 'PTIAffiliation',
				editor: new fm.TextField({
	            	allowBlank: true
	           	})
			}
			,{
				header: "User Name", 
				width: 90, 
				dataIndex: 'UserName',
				editor: new fm.TextField({
	            	allowBlank: false
	           	})
			}
			,{
				header: "Password", 
				width: 90, 
				dataIndex: 'Password',
				editor: new fm.TextField({
	            	allowBlank: false
	           	})
			},
			{
				header: "User Level", 
				width: 130, 
				sortable: true, 
				dataIndex: 'LevelSecurity',
				editor: userLevelCombo
			}
			
		]);
	
		// by default columns are sortable
	    colModel.defaultSortable = true;

	    // Create the Grid
		grid = new Ext.grid.EditorGridPanel({
	        store:    userStore,
	        cm:       colModel,
	        renderTo: renderDiv,
	        width:    850,
	        height:   450,
	        title:    '',
	        frame:    false
	    });
	
		grid.on('afteredit',saveGrid);
		grid.on('beforedestroy', function(){if(this.colModel) {this.colModel.setConfig([], false);}});
		function saveGrid(gridStuff) {
			var gridRow       = gridStuff.row;
			var cellValue     = gridStuff.value;
			var cellValueOrig = gridStuff.originalValue;
			var staffID       = gridStuff.record.data.StaffID;
			var cellField     = gridStuff.field;
			
			var dataString = {
							staffID:   staffID,
							newValue:  cellValue,
							fieldName: cellField,
							rowNumber: gridRow,
							origValue: cellValueOrig
			};
			jsonString = Object.toJSON(dataString);
			var params = 'handler=editUser&phpJSON='+jsonString;
		
			var ajaxResults = new Ajax.Request('ajaxDirector.php', {
				method: 'POST',
				parameters: params,	
				onSuccess: function(transport) {
					usersSupportObj.userEditReturn(whatUsers);
				},
				onFailure: function() {
					alert('Oops!');
				}		
			});
		}
		
		/*
		 * Load the data store
		 */
		userStore.load();
		
		/*
		 * Turn off columns based on what users we're looking at
		 */
		if (whatUsers == 'staff') {
			grid.getColumnModel().setHidden(6,true);
		} else if (whatUsers == 'resource') {
			grid.getColumnModel().setHidden(9,true);
		}			
	},
	userEditReturn : function (whatUsers) {
		if (whatUsers == 'staff') {
			var statusDiv = 'statusDiv0';
		} else if (whatUsers == 'resource') {
			var statusDiv = 'statusDiv1';
		}
		var message = 'User has been updated.';
		updateStatus(message,'success',statusDiv);
	
	}
}

var usersObj = {
	saveUser : function() {
		var password  = $F('uPassword');
		var passwordConfirm = $F('uPasswordConfirm');
				
		// Check for errors
		if (password != passwordConfirm) {
			var error = 1;
			var message = 'User password was not confirmed.';
			updateStatus(message,'error','statusDiv');
		} else {
			var userLevel = $F('uUserLevel');
			if ( (userLevel == 'Select...') || (userLevel == '') ) {
				userLevel = 0;
			}
			var formType = $F('formType');
			var dataString = {
				nameFirst:  $F('uNameFirst'),
				nameLast:   $F('uNameLast'),
				email:      $F('uEmail'),
				phone:      $F('uPhone'),
				userid:     $F('uUserName'),
				userLevel:  userLevel,
				password:   password,
				levelSecurity: 1,
				pti:        $F('uPTI'),
				formType:   formType
			};	
			
			jsonString = Object.toJSON(dataString);
			
			if (formType == 'userSharedResource') {
				var statusDiv = 'statusDiv1';
			} else if (formType == 'userStaff') {
				var statusDiv = 'statusDiv0';	
			}
			
			var params = 'handler=saveUser&jsonString='+jsonString;
			var ajaxResults = new Ajax.Request('ajaxDirector.php', {
				method: 'POST',
				parameters: params,
				onSuccess: function(transport) {
					var response = transport.responseText;
					
					if (response == 'duplicate user') {
						var message = 'This user is has already been created.';
						updateStatus(message,'error',statusDiv);	
					} else {
						var message = 'User has been saved.';
						updateStatus(message,'success',statusDiv);
						usersObj.returnSaveUser(transport.responseText);
					}					
				}
			});
		}
	},
	returnSaveUser : function() {
		usersSupportObj.cancelUser();		
		userStore.reload();	
	},
	deleteUser : function(userID) {
		var params = 'handler=deleteUser&userID='+userID;
		var ajaxResults = new Ajax.Request('ajaxDirector.php', {
			method: 'POST',
			parameters: params,
			onSuccess: function(transport) {
				userStore.reload();
			}
		});
	}
}

var viewTabContent = {
	content0Load : function() {
		usersSupportObj.renderUsersGrid('staff');
		$('content1').style.display = 'none';
	},
	content1Load : function() {
		usersSupportObj.renderUsersGrid('resource');
		/*
		 * Turn on content1 div
		 */
		$('content1').style.display = '';
	}
}

Ext.onReady(function() {
	//usersSupportObj.renderUsersGrid();
});